import 'package:dio/dio.dart';
import 'package:xws/models/baidu/baidu_token.dart';
import 'package:xws/models/baidu/goods_info.dart';
import 'package:xws/utils/log_util.dart';
import 'package:xws/utils/storage_util.dart';

import 'basic.dart';

/// 百度识图
class _BaiduAI {
  _BaiduAI._();

  /// 获取token的api
  static const String tokenApi = 'https://aip.baidubce.com/oauth/2.0/token';

  /// 通用物体识别api
  static const String api = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general';

  /// 缓存的token
  static String? accessToken;

  static String? get getToken {
    accessToken ??= getV<String>('baidu_ai_token');
    return accessToken;
  }
}

/// 识别物品
Future<String?> getGoodsInfo(String url) async {
  try {
    //获取token
    String? token = _BaiduAI.getToken;
    if (token == null) {
      token = await _getAccessToken();
      if (token != null) setV('baidu_ai_token', token);
    }

    if (token == null) return null;

    final Response<Map<String, dynamic>> r = await request<Map<String, dynamic>>(
      url: _BaiduAI.api + '?access_token=$token',
      method: 'post',
      contentType: 'application/x-www-form-urlencoded',
      data: <String, dynamic>{'url': url},
    );

    if (r.data == null) return null;

    final GoodsInfo info = GoodsInfo.fromJson(r.data!);

    if (info.errorCode != 0 || info.errorMsg.isNotEmpty) {
      error('识别物品 errorCode:${info.errorCode}');
      error('识别物品 errorMsg:${info.errorMsg}');
      return null;
    }

    if (info.result.isEmpty) {
      error('识别结果为空');
      return null;
    }

    return info.result.first.keyword;
  } catch (e) {
    error('识别物品出错:$e');
  }
}

/// 获取百度AI识图AccessToken
/// * error          | error_description             | 解释
/// * invalid_client | unknown client id             | API Key不正确
/// * invalid_client | Client authentication failed  | Secret Key不正确
Future<String?> _getAccessToken() async {
  try {
    final Response<Map<String, dynamic>> r = await request<Map<String, dynamic>>(
      url: _BaiduAI.tokenApi + '?grant_type=client_credentials&client_id=UMxlqkGRtBfaGgm9GTqwEUxt&client_secret=6yq2AVvjuosUW0GZuDzL3bQaFlK7lysa',
      method: 'post',
    );

    if (r.data == null) return null;

    final BaiduToken token = BaiduToken.fromJson(r.data!);

    if (token.error.isNotEmpty || token.errorDescription.isNotEmpty) {
      error('获取AccessToken error:${token.error}');
      error('获取AccessToken errorDescription:${token.errorDescription}');
      return null;
    }

    return token.accessToken;
  } catch (e) {
    error('获取百度AI识图AccessToken出错:$e');
  }
}
